﻿using System.Runtime.InteropServices;
using System;
using UtfprLibrary.Exceptions;
using UtfprLibrary.Libs;

namespace UtfprLibrary.Validations.Brazilian {
    public static class IE {
        /// <summary>
        /// 
        /// </summary>
        /// <exception cref="UtfprLibrary.Exceptions.UtfprValidationsException">Thrown when an exception occurs.</exception>
        public static bool Validate(string ie, string uf) {
            IntPtr h = IntPtr.Zero;
            try {
                //Elimina da string os traços, pontos e virgulas,
                ie = ie.Replace("-", "").Replace(".", "").Replace(",", "");

                h = UnmanagedLibraryManager.LoadLib("DllInscE32.dll");

                if (ConsisteInscricaoEstadual(ie, uf) == 0) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception ex) {
                throw new UtfprValidationsException(Properties.Resources.Validations_Brazilian_IE_ExMsg_Validate, ex);
            } finally {
                UnmanagedLibraryManager.FreeLib(h);
            }
        }

        /// <summary>
        /// http://www.sintegra.gov.br/download.html
        /// http://social.msdn.microsoft.com/forums/pt-BR/vscsharppt/thread/36f86855-a0c8-4090-b167-e0295769ed7e            
        /// </summary>
        /// <param name="ie">Inscrição Estadual</param>
        /// <param name="uf">Unidade Federativa</param>
        /// <returns>0 if it is valid, otherwise 1</returns>
        [DllImport("DllInscE32.dll")]
        public static extern int ConsisteInscricaoEstadual(string cInsc, string cUF);
    }
}
